import { defineStore } from 'pinia';
import { login, getInfo, yqLogin } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import router from '@/router';
import cache from '@/utils/cache';
import Cookies from 'js-cookie';

const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      userInfo: {},
      use_xtg: '0'
    };
  },
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password.trim();
      const appId = userInfo.appId;
      const isVerify = userInfo.isVerify;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login({ username, password, uuid, isVerify, appId })
          .then(({ data }) => {
            console.log(data)
            cache.local.setTokenloc(data.access_token);
            this.token = data.token;
            this.getInfo()
            resolve(data.token);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(res => {
            const user = res.user;
            this.userInfo = user;
            // const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.roles = ['ROLE_DEFAULT'];
            }
            this.name = user?.userName;
            // this.avatar = avatar;
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    logOut() {
      return new Promise((resolve, reject) => {
        try {
          this.token = '';
          this.roles = [];
          this.permissions = [];
          cache.session.remove('sessionObj');
          cache.local.remove('Admin-Token');
          // removeToken();
          // Cookies.remove('Admin-Token');
          router.replace({ path: '/' });
          resolve();
        } catch (error) {
          reject(error);
        }
        // logout(this.token).then(() => {
        //   this.token = ''
        //   this.roles = []
        //   this.permissions = []
        //   removeToken()
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      });
    }
  },
  getters: {
    double() {
      return this.count * 2;
    }
  },
  persist: {
    enabled: true, // 开启数据缓存 +++++++
  }
});

export default useUserStore;
